package com.numberone.master.modules.card.web;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.numberone.master.common.Interface.YiDong;
import com.numberone.master.common.beanvalidator.BeanValidators;
import com.numberone.master.common.config.Global;
import com.numberone.master.common.exception.RespResult;
import com.numberone.master.common.menu.RespCode;
import com.numberone.master.common.persistence.Page;
import com.numberone.master.common.web.BaseController;
import com.numberone.master.common.utils.DateUtils;
import com.numberone.master.common.utils.JsonUtils;
import com.numberone.master.common.utils.StringUtils;
import com.numberone.master.common.utils.excel.ExportExcel;
import com.numberone.master.modules.card.entity.Card;
import com.numberone.master.modules.card.service.CardService;
import com.numberone.master.modules.recharge.entity.Package;
import com.numberone.master.modules.recharge.service.PackageService;
import com.numberone.master.modules.rsa.service.RsaService;
import com.numberone.master.modules.sys.dao.OfficeCardDao;
import com.numberone.master.modules.sys.dao.UserDao;
import com.numberone.master.modules.sys.entity.Area;
import com.numberone.master.modules.sys.entity.Dict;
import com.numberone.master.modules.sys.entity.DictInfo;
import com.numberone.master.modules.sys.entity.Office;
import com.numberone.master.modules.sys.entity.OfficeCard;
import com.numberone.master.modules.sys.entity.User;
import com.numberone.master.modules.sys.service.DictService;
import com.numberone.master.modules.sys.service.OfficeService;
import com.numberone.master.modules.sys.utils.UserUtils;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

/**
 * 物联网卡Controller
 * @author chegkang
 * @version 2018-02-01
 */
@Controller
@RequestMapping(value = "${adminPath}/card/card")
public class CardController extends BaseController {

	@Autowired
	private CardService cardService;
	
	@Autowired
	private RsaService rsaService;
	
	@Autowired
	private OfficeCardDao officeCardDao;
	
	@Autowired
	private UserDao userDao;
	
	@Autowired
	private PackageService packageService;
	
	@Autowired
	private OfficeService officeService;

	 /**
     * 根据id查询一条数据
     * @param id
     * @return
     */
	@ModelAttribute
	public Card get(@RequestParam(required=false) String id) {
		Card entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = cardService.get(id);
		}
		if (entity == null){
			entity = new Card();
		}
		return entity;
	}
	
	/**
	 * 查询卡的实时流量和状态
	 * @param iccid
	 * @param type
	 * @param EBID
	 * @param request
	 * @return
	 * @throws JsonProcessingException 
	 */
	@RequestMapping(value = {"selectCardInfo", ""})
	@ResponseBody
	public RespResult selectCardInfo(@RequestParam(value = "iccid", required = false)String iccid,
			@RequestParam(value = "areaId", required = false)String areaId,
			@RequestParam(value = "ebid", required = false)String ebid,
			HttpServletRequest request) throws JsonProcessingException {
		if(StringUtils.equals(areaId, "5")){
		 	String res = cardService.getCardInfo(iccid, ebid);
		 	Map<String,Object> msgMap = JsonUtils.fromJson(res);
			String status = (String)msgMap.get("status");
			if(StringUtils.equals(status, "0")){
				return RespResult.getInstance(RespCode.SUCCESS,res.replaceAll("status","STATUS"));
			}else{
				return RespResult.getInstance("-1","查询失败");
			}
		}else{
			String transid = rsaService.getTransid();
		 	String res  = YiDong.yiDongPost(ebid, areaId, iccid, transid);
		 	Map<String,Object> msgMap = JsonUtils.fromJson(res);
			String status = (String)msgMap.get("status");
			if(StringUtils.equals(status, "0")){
				return RespResult.getInstance(RespCode.SUCCESS,res);
			}else{
				return RespResult.getInstance("-1","查询失败");
			}
		}
		
	}


	 /**
     * list列表
     * @param card
     * @param request
     * @param response
     * @param model
     * @return
     */
	@RequiresPermissions("card:card:list")
	@RequestMapping(value = {"list", ""})
	public String list(Card card, HttpServletRequest request, HttpServletResponse response, Model model) {
		String officeId = UserUtils.getUser().getOffice().getId();
		card.setOfficeId(officeId);
		Page<Card> page = cardService.findPage(new Page<Card>(request, response), card); 
		model.addAttribute("page", page);
		model.addAttribute("officeName", UserUtils.getUser().getOffice().getName());
		//打开所属的用户
		List<User> userList = userDao.findUserListByOfficeId(officeId);
		model.addAttribute("userList", userList);
		model.addAttribute("officeId", officeId);
		return "modules/card/cardList";
	}
	
	
	/**
	 * 流量预警列表
	 * @param card
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("card:card:thresholdList")
	@RequestMapping(value = {"threshold_list", ""})
	public String thresholdList(Card card, HttpServletRequest request, HttpServletResponse response, Model model) {
		String officeId = UserUtils.getUser().getOffice().getId();
		card.setWarning("100");
		card.setOfficeId(officeId);
		Page<Card> page = cardService.findPage(new Page<Card>(request, response), card); 
		model.addAttribute("page", page);
		return "modules/card/cardThresholdList";
	}
	
	/**
	 * 重新分配列表
	 * @param card
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("card:card:againList")
	@RequestMapping(value = {"again_list", ""})
	public String againList(Card card, HttpServletRequest request, HttpServletResponse response, Model model) {		
		String officeId = UserUtils.getUser().getOffice().getId();
		model.addAttribute("officeId", officeId);
		card.setOfficeId(officeId);
		Page<Card> page = cardService.findAgainPageList(new Page<Card>(request, response), card); 
		model.addAttribute("page", page);
		return "modules/card/cardAgainList";
	}

	/**
     * 打开增加页面
     * @return
     */
	@RequiresPermissions("card:card:save")
	@RequestMapping(value = "openSave")
	public String openSave() {
		return "modules/card/cardSave";
	}


	/**
	 * 打开修改页面
	 * @param card
	 * @param model
	 * @return
	 */
	@RequiresPermissions("card:card:update")
	@RequestMapping(value = "openUpdate")
	public String openUpdate(Card card, Model model) {
		model.addAttribute("card", card);
		return "modules/card/cardUpdate";
	}

	/**
	 * 添加
	 * @param card
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("card:card:save")
	@RequestMapping(value = "save")
	public String save(Card card, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, card)){
			return openSave();
		}
		cardService.save(card);
		addMessage(redirectAttributes, "添加卡成功");
		return "redirect:"+Global.getAdminPath()+"/card/card/?repage";
	}

	/**
	 * 修改
	 * @param card
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("card:card:update")
	@RequestMapping(value = "update")
	public String update(Card card, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, card)){
			return openUpdate(card, model);
		}
		cardService.update(card);
		addMessage(redirectAttributes, "修改卡成功");
		return "redirect:"+Global.getAdminPath()+"/card/card/?repage";
	}

	 /**
     * 删除
     * @param card
     * @param redirectAttributes
     * @return
     */
	@RequiresPermissions("card:card:delete")
	@RequestMapping(value = "delete")
	public String delete(Card card, RedirectAttributes redirectAttributes) {
		cardService.delete(card);
		addMessage(redirectAttributes, "删除卡成功");
		return "redirect:"+Global.getAdminPath()+"/card/card/?repage";
	}
	
	/**
	 * 批量删除
	 * @param card
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("card:card:delete")
	@RequestMapping(value = "batchDelete")
	public String batchDelete(String[] ids, RedirectAttributes redirectAttributes) {
		int num = 0;
		for (int i = 0; i < ids.length; i++) {
			cardService.delete(cardService.get(ids[i]));
			num++;
		}
		addMessage(redirectAttributes, "成功删除"+num+"张流量卡");
		return "redirect:"+Global.getAdminPath()+"/card/card/list?repage";
	}
	
	/**
	 * 导入流量卡数据
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("card:card:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		//获取当前登录人信息
		User user = UserUtils.getUser();
/*		String fileName = file.getName();
		if (StringUtils.isBlank(fileName)){
			addMessage(redirectAttributes, "导入文档为空！");
			return "redirect:" + adminPath + "/card/card/list?repage";
		}
		if(fileName.toLowerCase().endsWith("xlsx")){
			addMessage(redirectAttributes, "暂时不支持xlsx格式文档！");
			return "redirect:" + adminPath + "/card/card/list?repage";
		}*/
		try {
		 	InputStream is = file.getInputStream();  
            //得到excel  
            Workbook workbook = Workbook.getWorkbook(is);  
            //得到sheet  
            Sheet sheet = workbook.getSheet(0);  
            //得到列数  
            int colsNum = sheet.getColumns();
            //得到行数  
            int rowsNum = sheet.getRows();  
            //单元格  
            Cell cell;  
            int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
            for (int i = 2; i < rowsNum; i++) {//我的excel第一行是标题,所以 i从1开始  
            		Card card = new Card();
                    cell = sheet.getCell(0, i);
                    String iccid = cell.getContents();
                    cell = sheet.getCell(1, i);
                    String pkg = cell.getContents();
                    cell = sheet.getCell(2, i);
                    String cardNo = cell.getContents();
                    cell = sheet.getCell(3, i);
                    String areaId = cell.getContents();
                    card.setOperator(user.getOffice().getId());//操作人
					card.setBrand(new Long(1));
					card.setBatchid(new Long(4));//批次
					card.setJituancode(new Long(0));
					card.setTixphoneno("13376099997");
					card.setDxgn("1");
					card.setYygn("1");
					card.setRemark("测试期1个月，沉默期6个月");
					card.setStatecontrol("0");
					card.setFlowcontrol("11");
					card.setCreateDate(new Date());
					card.setCreateBy(user);
					card.setUpdateBy(user);
					card.setOffice(user.getOffice());
					card.setUpdateDate(new Date());
					card.setCardStatus(new Long(1));
					//添加exl表里面的数据
					card.setIccid(iccid);
					card.setPkg(pkg);
					card.setPhonenumber(cardNo);
					Area area = new Area();
					area.setId(areaId);
					card.setArea(area);
					BeanValidators.validateWithException(validator, card);
					cardService.save(card);
					//根据iccid查询
					Card cardInfo = cardService.getCardInfoByCCID(card.getIccid());
					//添加关联信息
					OfficeCard c = new OfficeCard();
					c.setOfficeId("1");
					c.setCardId(cardInfo.getId());
					c.setState("2");
					officeCardDao.insert(c);
					successNum++;
                    
            }  
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条流量卡信息，导入信息如下：");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条流量卡信息"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入流量卡信息失败！失败信息："+e.getMessage());
			return "redirect:" + adminPath + "/card/card/list?repage";
		}
		return "redirect:" + adminPath + "/card/card/list?repage";
    }
	
	/**
	 * 下载导入流量卡数据模板
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("card:card:Import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "流量卡数据导入模板.xls";
    		List<Card> list = Lists.newArrayList();
    		Card card = new Card();
    		card.setPhonenumber("1064843710978");
    		card.setIccid("898602B4071770340988");
    		new ExportExcel("流量卡数据模板", Card.class, 2).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "流量信息模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/card/card/list?repage";
    }
	
	/**
	 * 导出流量卡数据
	 * @param user
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("card:card:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(Card card, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "流量卡数据"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            List<Card> list = cardService.findCardList(card);
    		new ExportExcel("流量卡数据", Card.class).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出流量卡新数据失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/card/card/list?repage";
    }
	
	
	/**
	 * 最终用户分配
	 * @param ids
	 * @param userId
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("card:card:setUpUser")
	@RequestMapping(value = "setUpUser")
	public String setUpUser(String[] cardIds,String userId,RedirectAttributes redirectAttributes) {
		//获取当前登录人用户信息
		String id = UserUtils.getUser().getId();
		if(StringUtils.equals(id, userId)){
			addMessage(redirectAttributes, "分配失败！请勿将流量卡分配给自己。");
			return "redirect:" + adminPath + "/card/card/list?repage";
		}
		//查询是否存在已经分配的流量卡
		int isExistence = officeCardDao.isExistenceUser(StringUtils.join(cardIds,","));
		if(isExistence > 0){
			addMessage(redirectAttributes, "分配失败！"+isExistence+"张流量卡已被分配");
			return "redirect:" + adminPath + "/card/card/list?repage";
		}else{
			int num = 0;
			for (int i = 0; i < cardIds.length; i++) {
				Card c = new Card();
				c.setId(cardIds[i]);
				c.setUpdateBy(UserUtils.getUser());
				c.setUpdateDate(new Date());
				c.setCardStatus(new Long(2));
				c.setMemid(Long.valueOf(userId));
				cardService.updateSetUser(c);
				num++;
			}
			addMessage(redirectAttributes, "成功分配"+num+"张流量卡给<"+UserUtils.get(userId).getName()+">用户");
			return "redirect:"+adminPath+"/card/card/list?repage";
		}
	}
	
	/**
	 * 设置流量预警值
	 * @param ids  主键id
	 * @param warning
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("card:card:threshold")
	@RequestMapping(value = "threshold")
	public String threshold(String[] ids,String warning,RedirectAttributes redirectAttributes) {
		if(!warning.matches("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$")){
			addMessage(redirectAttributes, "设置失败！预警值必须是数字");
			return "redirect:" + adminPath + "/card/card/list?repage";
		}
		User user = UserUtils.getUser();
			int num = 0;
			for (int i = 0; i < ids.length; i++) {
				Card c = new Card();
				c.setId(ids[i]);
				c.setWarning(warning);
				c.setUpdateDate(new Date());
				c.setUpdateBy(user);
				cardService.updateThreshold(c);
				num++;
			}
			addMessage(redirectAttributes, "成功设置"+num+"张流量卡预警值");
			return "redirect:"+adminPath+"/card/card/list?repage";
	}
	
	
	/**
	 * 批量分配
	 * @param ids
	 * @param officeId
	 * @param redirectAttributes
	 * @param videPriceValue 叠加套餐价格
	 * @return
	 */
	@RequiresPermissions("card:card:distribution")
	@RequestMapping(value = "distribution")
	public String distribution(String videPriceValue,String[] ids,String company,String mainPriceValue,String taocanType,RedirectAttributes redirectAttributes) {
		if(StringUtils.isBlank(company)){
			addMessage(redirectAttributes, "分配失败,请选择代理商。");
			return "redirect:" + adminPath + "/card/card/list?repage";
		}
		if(StringUtils.isBlank(mainPriceValue) || StringUtils.isBlank(taocanType) || StringUtils.isBlank(company) || ids.length == 0){
			addMessage(redirectAttributes, "分配失败！参数错误。");
			return "redirect:" + adminPath + "/card/card/list?repage";
		}
		if(!mainPriceValue.matches("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$") || !videPriceValue.matches("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$")){
			addMessage(redirectAttributes, "分配失败！销售价格必须是正确的金额，保留2位小数。");
			return "redirect:" + adminPath + "/card/card/list?repage";
		}
		//获取当前人
		String id = UserUtils.getUser().getOffice().getId();
		if(StringUtils.equals(id, company)){
			addMessage(redirectAttributes, "分配失败！请勿将流量卡分配给自己。");
			return "redirect:" + adminPath + "/card/card/list?repage";
		}
		//查询是否存在已经分配的流量卡
		int isExistenceUser = officeCardDao.isExistenceUser(StringUtils.join(ids,","));
		if(isExistenceUser > 0){
			addMessage(redirectAttributes, "分配失败！"+isExistenceUser+"张流量卡已有最终所属用户");
			return "redirect:" + adminPath + "/card/card/list?repage";
		}
		//查询是否存在已经分配的流量卡
		int isExistence = officeCardDao.isExistence(StringUtils.join(ids,","),id);
		if(isExistence > 0){
			addMessage(redirectAttributes, "分配失败！"+isExistence+"张流量卡已被分配");
			return "redirect:" + adminPath + "/card/card/list?repage";
		}else{
			//查询自己的套餐信息
			Package mainOwnPack = packageService.isPackageCount(id, taocanType);//主套餐
			Package videOwnPack = packageService.isPackageCount(id, "7");//叠加套餐
			if(mainOwnPack == null || videOwnPack == null){
				addMessage(redirectAttributes, "分配失败！未查询到自己的套餐信息，请先联系上级代理商添加套餐。");
				return "redirect:" + adminPath + "/card/card/list?repage";
			}
			Double mainOwnPrice = new Double(mainPriceValue);//主套餐销售价格
			Double videOwnPrice = new Double(videPriceValue);//叠加套餐销售价格
			BigDecimal data1 = new BigDecimal(mainOwnPrice);
			BigDecimal data2 = new BigDecimal(videOwnPrice);
			BigDecimal data3 = new BigDecimal(mainOwnPack.getPrice());
			BigDecimal data4 = new BigDecimal(videOwnPack.getPrice());
			if(data1.compareTo(data3) == -1){
				addMessage(redirectAttributes, "分配失败！主套餐销售价格不得低于"+mainOwnPack.getPrice()+"元");
				return "redirect:" + adminPath + "/card/card/list?repage";
			}
			if(data2.compareTo(data4) == -1){
				addMessage(redirectAttributes, "分配失败！叠加套餐销售价格不得低于"+mainOwnPack.getPrice()+"元");
				return "redirect:" + adminPath + "/card/card/list?repage";
			}
			//判断套餐是否存在，存在就修改
			Package mainDisPack = packageService.isPackageCount(company, taocanType);//分配人所属的套餐
			Package videDisPack = packageService.isPackageCount(company, "7");//叠加套餐
			Office office = officeService.get(company);//分配人
			if(mainDisPack == null){
				Package ps = new Package();
				ps.setCreateDate(new Date());
				ps.setType(mainOwnPack.getType());
				ps.setTctype(mainOwnPack.getTctype());
				ps.setTcId(mainOwnPack.getTcId());
				ps.setPrice(new Double(mainPriceValue));
				ps.setSalePrice(new Double(mainPriceValue));
				ps.setOffice(office);
				ps.setCreateBy(UserUtils.getUser());
				ps.setDelFlag("0");
				ps.setCreateId(id);
				packageService.insert(ps);
			}else{
				//修改
				mainDisPack.setOffice(office);
				mainDisPack.setUpdateBy(UserUtils.getUser());
				mainDisPack.setUpdateDate(new Date());
				mainDisPack.setPrice(new Double(mainPriceValue));
				packageService.update(mainDisPack);
			}
			if(videDisPack == null){
				//增加叠加套餐信息
				Package ps = new Package();
				ps.setCreateDate(new Date());
				ps.setType(videOwnPack.getType());
				ps.setTctype(videOwnPack.getTctype());
				ps.setTcId(videOwnPack.getTcId());
				ps.setPrice(new Double(videPriceValue));
				ps.setSalePrice(new Double(videPriceValue));
				ps.setOffice(office);
				ps.setCreateBy(UserUtils.getUser());
				ps.setDelFlag("0");
				ps.setCreateId(id);
				packageService.insert(ps);
			}else{
				//修改
				videDisPack.setOffice(office);
				videDisPack.setUpdateBy(UserUtils.getUser());
				videDisPack.setUpdateDate(new Date());
				videDisPack.setPrice(new Double(videPriceValue));
				packageService.update(videDisPack);
			}
			//分配卡
			int num = 0;
			for (int i = 0; i < ids.length; i++) {
				//修改之前分配数据
				officeCardDao.updateOfficeCardByCardId(ids[i], company, id);
				OfficeCard o = new OfficeCard();
				o.setOfficeId(company);
				o.setCardId(ids[i]);
				o.setState("2");
				officeCardDao.insert(o);
				num++;
			}
			addMessage(redirectAttributes, "成功分配"+num+"张流量卡");
			return "redirect:"+adminPath+"/card/card/list?repage";
		}
	}
	
	/**
	 * 重新分配
	 * @param videPriceValue 叠加套餐价格
	 * @param ids 主键id
	 * @param company 分配给的代理人
	 * @param mainPriceValue 
	 * @param taocanType
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("card:card:againDistribution")
	@RequestMapping(value = "againDistribution")
	public String againDistribution(String videPriceValue,String[] ids,String company,String mainPriceValue,String taocanType,RedirectAttributes redirectAttributes) {
		if(StringUtils.isBlank(company)){
			addMessage(redirectAttributes, "分配失败,请选择代理商。");
			return "redirect:" + adminPath + "/card/card/again_list?repage";
		}
		if(StringUtils.isBlank(mainPriceValue) || StringUtils.isBlank(taocanType) || StringUtils.isBlank(company) || ids.length == 0){
			addMessage(redirectAttributes, "分配失败！参数错误。");
			return "redirect:" + adminPath + "/card/card/again_list?repage";
		}
		if(!mainPriceValue.matches("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$") || !videPriceValue.matches("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$")){
			addMessage(redirectAttributes, "分配失败！销售价格必须是数字。");
			return "redirect:" + adminPath + "/card/card/again_list?repage";
		}
		//获取当前人
		String id = UserUtils.getUser().getOffice().getId();
		if(StringUtils.equals(id, company)){
			addMessage(redirectAttributes, "分配失败！请勿将流量卡分配给自己。");
			return "redirect:" + adminPath + "/card/card/again_list?repage";
		}
		//查询是否存在已经分配的流量卡
		int isExistenceUser = officeCardDao.isExistenceUser(StringUtils.join(ids,","));
		if(isExistenceUser > 0){
			addMessage(redirectAttributes, "分配失败！"+isExistenceUser+"张流量卡已有最终所属用户");
			return "redirect:" + adminPath + "/card/card/again_list?repage";
		}else{
			//查询自己的套餐信息
			Package mainOwnPack = packageService.isPackageCount(id, taocanType);//主套餐
			Package videOwnPack = packageService.isPackageCount(id, "7");//叠加套餐
			if(mainOwnPack == null || videOwnPack == null){
				addMessage(redirectAttributes, "分配失败！未查询到自己的套餐信息，请先联系上级代理商添加套餐。");
				return "redirect:" + adminPath + "/card/card/again_list?repage";
			}
			Double mainOwnPrice = new Double(mainPriceValue);//主套餐销售价格
			Double videOwnPrice = new Double(videPriceValue);//叠加套餐销售价格
			BigDecimal data1 = new BigDecimal(mainOwnPrice);
			BigDecimal data2 = new BigDecimal(videOwnPrice);
			BigDecimal data3 = new BigDecimal(mainOwnPack.getPrice());
			BigDecimal data4 = new BigDecimal(videOwnPack.getPrice());
			if(data1.compareTo(data3) == -1){
				addMessage(redirectAttributes, "分配失败！主套餐销售价格不得低于"+mainOwnPack.getPrice()+"元");
				return "redirect:" + adminPath + "/card/card/again_list?repage";
			}
			if(data2.compareTo(data4) == -1){
				addMessage(redirectAttributes, "分配失败！叠加套餐销售价格不得低于"+mainOwnPack.getPrice()+"元");
				return "redirect:" + adminPath + "/card/card/again_list?repage";
			}
			//判断套餐是否存在，存在就修改
			Package mainDisPack = packageService.isPackageCount(company, taocanType);//分配人所属的套餐
			Package videDisPack = packageService.isPackageCount(company, "7");//叠加套餐
			Office office = officeService.get(company);//分配人
			if(mainDisPack == null){
				Package ps = new Package();
				ps.setCreateDate(new Date());
				ps.setType(mainOwnPack.getType());
				ps.setTctype(mainOwnPack.getTctype());
				ps.setTcId(mainOwnPack.getTcId());
				ps.setPrice(new Double(mainPriceValue));
				ps.setSalePrice(new Double(mainPriceValue));
				ps.setOffice(office);
				ps.setCreateBy(UserUtils.getUser());
				ps.setDelFlag("0");
				ps.setCreateId(id);
				packageService.insert(ps);
			}else{
				//修改
				mainDisPack.setOffice(office);
				mainDisPack.setUpdateBy(UserUtils.getUser());
				mainDisPack.setUpdateDate(new Date());
				mainDisPack.setPrice(new Double(mainPriceValue));
				packageService.update(mainDisPack);
			}
			if(videDisPack == null){
				//增加叠加套餐信息
				Package ps = new Package();
				ps.setCreateDate(new Date());
				ps.setType(videOwnPack.getType());
				ps.setTctype(videOwnPack.getTctype());
				ps.setTcId(videOwnPack.getTcId());
				ps.setPrice(new Double(videPriceValue));
				ps.setSalePrice(new Double(videPriceValue));
				ps.setOffice(office);
				ps.setCreateBy(UserUtils.getUser());
				ps.setDelFlag("0");
				ps.setCreateId(id);
				packageService.insert(ps);
			}else{
				//修改
				videDisPack.setOffice(office);
				videDisPack.setUpdateBy(UserUtils.getUser());
				videDisPack.setUpdateDate(new Date());
				videDisPack.setPrice(new Double(videPriceValue));
				packageService.update(videDisPack);
			}
			//分配卡
			int num = 0;
			
			for (int i = 0; i < ids.length; i++) {
				List<String> list = new ArrayList<>();
				delets(UserUtils.getUser().getOffice().getId(), ids[i], list);
				for (int j = 0; j < list.size(); j++) {
					officeCardDao.deleteInfo(ids[i], list.get(j));
				}
				//修改之前分配数据
				officeCardDao.updateOfficeInfo(ids[i], company, id);
				OfficeCard o = new OfficeCard();
				o.setOfficeId(company);
				o.setCardId(ids[i]);
				o.setState("2");
				officeCardDao.insert(o);
				num++;
			}
			addMessage(redirectAttributes, "成功重新分配"+num+"张流量卡");
			return "redirect:"+adminPath+"/card/card/again_list?repage";
		}
	}
	
	//循环删除所属的卡信息
	public List<String> delets(String officeId,String cardId,List<String> list){
		//查询是否存在
		OfficeCard c = officeCardDao.selectOfficeCardByIdAnCardId(cardId, officeId);
		if(StringUtils.isNotEmpty(officeId) && StringUtils.isNotEmpty(cardId)){
			if(c != null && StringUtils.isNotEmpty(c.getToaId())){
				list.add(c.getToaId());
				delets(c.getToaId(), cardId,list);
			}
		}
		return list;
	}
	
	/**
	 * 判断卡是否是同一种类
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = {"isKindCard", ""})
	@ResponseBody
	public Map<String,Object> isKindCard(String id){
		Map<String,Object> map = new HashMap<>();
		if(StringUtils.isBlank(id)){
			map.put("code", "1");
			map.put("taocanType", "");
			map.put("taocanName", "请选择流量卡");
			return map;
		}
		String[] ids = id.split(",");
		if(ids.length == 0){
			map.put("code", "1");
			map.put("taocanType", "");
			map.put("taocanName", "请选择流量卡");
			return map;
		}
		String taocanType = cardService.get(ids[0]).getPkg();
		int count = cardService.getCardByIds(StringUtils.join(ids,","),taocanType);
		if(count == ids.length ){
			Package packages = packageService.isPackageCount(UserUtils.getUser().getOffice().getId(), taocanType);
			if(packages == null){
				map.put("code", "1");
				map.put("taocanType", "");
				map.put("taocanName", "未知套餐，分配失败。");
				return map;
			}
			//查询叠加包套餐
			Package p = packageService.isPackageCount(UserUtils.getUser().getOffice().getId(), "7");
			if(p != null){
				map.put("videTaocanName", p.getTctype());
				map.put("videTcPrice", p.getPrice());
			}
			map.put("code", "0");
			map.put("taocanType", taocanType);
			map.put("taocanName", packages.getTctype());
			map.put("tcPrice", packages.getPrice());
		}else{
			map.put("code", "1");
			map.put("taocanType", "");
			map.put("taocanName", "套餐不一致，请选择套餐一致的流量卡。");
			return map;
		}
		return map;
	}
	
	
	@RequestMapping(value = {"getSalePrice", ""})
	@ResponseBody
	public Map<String,Object> getSalePrice(String id,String taocanType){
		Map<String,Object> map = new HashMap<>();
		Package mainPackage = packageService.isPackageCount(id, taocanType);
		if(mainPackage == null){
			map.put("mainPrice", "");
		}else{
			map.put("mainPrice", mainPackage.getPrice());
		}
		Package basePackage = packageService.isPackageCount(id, "7");
		if(basePackage == null){
			map.put("basePrice", "");
		}else{
			map.put("basePrice", basePackage.getPrice());
		}
		return map;
	}
	
}